package com.pktechan.manage.controller;


import com.pktechan.manage.base.annotation.Auth;
import com.pktechan.manage.base.annotation.RecordOperateLog;
import com.pktechan.manage.entity.SysOperate;
import com.pktechan.manage.entity.SysUser;
import com.pktechan.manage.enumeration.ModelTypeEnum;
import com.pktechan.manage.enumeration.OperateLogTypeEnum;
import com.pktechan.manage.enumeration.OperateTypeEnum;
import com.pktechan.manage.enumeration.YesOrNoEnum;
import com.pktechan.manage.service.LoginService;
import com.pktechan.manage.service.SysOperateService;
import com.pktechan.manage.utils.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * <br>
 * <b>功能：</b>系统控制器类，提供一些类似登录、登出等系统级别的方法<br>
 * <b>作者：</b>Wang Jiahao<br>
 * <b>日期：</b> Mar 23, 2016 <br>
 * <b>版权所有：<b>版权所有(C) 2016，高晟金服<br>
 */
@Controller
@RequestMapping("/sys")
public class SystemController {

    private final static Logger LOGGER = LoggerFactory.getLogger(SystemController.class);

    @Autowired
    private LoginService loginService;
    @Autowired
    private SysOperateService sysOperateService;


    /**
     * 用户登录
     * TA清算
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/dologin", method = RequestMethod.POST)
    public void doLogin(@RequestBody SysUser sysUser, HttpServletRequest request,
                        HttpServletResponse response) throws Exception {
        LOGGER.debug("user login");
        // 根据用户登录名获取用户信息
        SysUser returnEntity = loginService.validateUser(sysUser);

        if (returnEntity != null) {
            // 获取用户信息
            SessionUtils.setUser(request, returnEntity);

            StringBuffer sbCurrentUserOperate = new StringBuffer();
            List<SysOperate> modularAndOperateList = null;
            //获取用户权限,如果是超级管理员，给与所有权限
            if (returnEntity.getSuperAdmin() == YesOrNoEnum.YES.getICode()) {
                //查询系统中的所有操作
                modularAndOperateList = sysOperateService.queryAllOperateList();
            } else {
                //根据用户的角色查询处对应的权限
                modularAndOperateList = sysOperateService.queryOperateList(returnEntity.getId());
            }

            Map<String, SysOperate> modularMap = new HashMap<String, SysOperate>();
            for (SysOperate sysOperate : modularAndOperateList) {
                if (!StringUtil.isEmpty(sysOperate.getKeyName())) {
                    sbCurrentUserOperate.append(sysOperate.getKeyName()).append(SystemConstants.SIGN_COMMA);
                }
                //将类型是菜单的,存放在集合类中,返回页面生成菜单
                if (OperateTypeEnum.MENU.getCode().equals(sysOperate.getOperateType())) {
                    modularMap.put(String.valueOf(sysOperate.getId()), sysOperate);
                }
            }
            SessionUtils.setModularMap(request, modularMap);
            SessionUtils.setCurrentOperateString(request, sbCurrentUserOperate.toString());
            LOGGER.debug(": " + JacksonJsonUtil.beanToJson(returnEntity));
//            systemOperateLogService.createLoginLog(sysUser.getAccount() + "(" + GetIpUtil.getIpAddr(request) + ")", YesOrNoEnum.YES);
            HtmlUtil.writerSuccessJson(response);
        } else {
            // 查询返回对象为空，说明没有匹配的用户
//            systemOperateLogService.createLoginLog(sysUser.getAccount() + "(" + GetIpUtil.getIpAddr(request) + ")", YesOrNoEnum.NO);
            HtmlUtil.writerFailJson(response, "用户名或密码错误！");
        }
    }

    /**
     *判断是否有该权限
     * @param request
     * @return
     */
    @RequestMapping(value = "/haspermission/{permissionId}", method = RequestMethod.GET)
    @Auth()
    public void hasPermission(@PathVariable String permissionId, HttpServletRequest request,
                              HttpServletResponse response) throws Exception {
        LOGGER.debug("hasPermission");
        String currentOperateString = SessionUtils.getCurrentOperateString(request);
        if (!StringUtil.isEmpty(currentOperateString)) {
            if (currentOperateString.indexOf(permissionId + SystemConstants.SIGN_COMMA) >= 0) {
                HtmlUtil.writerSuccessJson(response, true);
            } else {
                HtmlUtil.writerSuccessJson(response, false);
            }

        } else {
            HtmlUtil.writerSuccessJson(response, false);
        }
    }

    /**
     * 获取用户权限
     *
     * @param request
     * @param response
     */
    @RequestMapping(value = "/modular", method = RequestMethod.GET)
    public void modular(HttpServletRequest request, HttpServletResponse response) {
        HtmlUtil.writerSuccessJson(response, SessionUtils.getModularMap(request));
    }

    /**
     * 登出 注销
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/dologout", method = RequestMethod.GET)
    @RecordOperateLog(modelType = ModelTypeEnum.LOGOUT, operateType = OperateLogTypeEnum.OTHER)
    public void doLoginOut(HttpServletRequest request, HttpServletResponse response) throws Exception {
        SessionUtils.removeUser(request);
        HtmlUtil.writerSuccessJson(response);
    }

    /**
     * 获取当前登录用户信息
     *
     * @param request
     * @param response
     */
    @RequestMapping(value = "/userInfo", method = RequestMethod.GET)
    @Auth()
    public void getCurrentUserInfo(HttpServletRequest request, HttpServletResponse response) {
        try {
            HtmlUtil.writerSuccessJson(response, SessionUtils.getUser(request));
        } catch (Exception e) {
            HtmlUtil.writerFailJson(response, e.getMessage());
            LOGGER.error(e.getMessage(), e);
        }
    }


    /**
     * 微信扫码登录
     *
     * @param request
     * @param response
     */
    @RequestMapping(value = "/scanQrCodeLogin", method={RequestMethod.POST, RequestMethod.GET})
    public ModelAndView scanQrCodeLogin(@RequestParam String employeeNo, HttpServletRequest request, HttpServletResponse response) throws Exception {
        try {
            LOGGER.info("[微信扫码登录]");
//            String mode = "scanQrCodeLogin";
//            if (StringUtil.isValid(employeeNo) != true) {
//                throw new Exception("缺少员工号，登录失败!");
//            }
//            SysUser sysUser = new SysUser();
//            sysUser.setCertNo(employeeNo);
//            //根据certNo获取用户信息
//            SysUser returnEntity = loginService.validateUserByCertNo(sysUser);
//            if (returnEntity != null) {
//                sysUser.setId(returnEntity.getId());
//                sysUser.setName(returnEntity.getName());
//                sysUser.setSuperAdmin(returnEntity.getSuperAdmin());
//                SessionUtils.setUser(request, sysUser);
//                this.goLogin(returnEntity,mode,request,response);
//                response.sendRedirect("/toIndex.html");
//            } else {
//                // 查询返回对象为空，说明没有匹配的用户
//                throw new Exception("系统还未为您分配后台账户，请联系管理员!");
//            }
        } catch (Exception e) {
            e.printStackTrace();
            ModelAndView mav = new ModelAndView("/errorJsp/errorMessage");
            mav.getModel().put("error",e.getMessage());
            return mav;
        }
        return  null;
    }

    /**
     * 抽取登陆公共方法
     * @param request
     * @param response
     */
    @RequestMapping(value = "/goLogin", method = RequestMethod.GET)
    public void goLogin(SysUser sysUser, String mode, HttpServletRequest request, HttpServletResponse response) throws Exception {
        // 获取用户信息
        SessionUtils.setUser(request, sysUser);

        StringBuffer sbCurrentUserOperate = new StringBuffer();
        List<SysOperate> modularAndOperateList = null;
        //获取用户权限,如果是超级管理员，给与所有权限
        if (sysUser.getSuperAdmin() == YesOrNoEnum.YES.getICode()) {
            //查询系统中的所有操作
            modularAndOperateList = sysOperateService.queryAllOperateList();
        } else {
            //根据用户的角色查询处对应的权限
            modularAndOperateList = sysOperateService.queryOperateList(sysUser.getId());
        }

        Map<String, SysOperate> modularMap = new HashMap<String, SysOperate>();
        for (SysOperate modularAndOperate : modularAndOperateList) {
            if (!StringUtil.isEmpty(modularAndOperate.getKeyName())) {
                sbCurrentUserOperate.append(modularAndOperate.getKeyName()).append(SystemConstants.SIGN_COMMA);
            }
            //将类型是菜单的,存放在集合类中,返回页面生成菜单
            if (OperateTypeEnum.MENU.getCode().equals(modularAndOperate.getOperateType())) {
                modularMap.put(String.valueOf(modularAndOperate.getId()), modularAndOperate);
            }
        }
        SessionUtils.setModularMap(request, modularMap);
        SessionUtils.setCurrentOperateString(request, sbCurrentUserOperate.toString());
        LOGGER.debug(": " + JacksonJsonUtil.beanToJson(sysUser));
        if (mode.equals("dologin")) {
            HtmlUtil.writerSuccessJson(response);
        }
    }

    /**
     * 根据配置文件获取页面名称
     *
     * @param request
     * @param response
     */
    @RequestMapping(value = "/urlName", method = RequestMethod.GET)
    public void urlName(HttpServletRequest request, HttpServletResponse response) {
        String urlName = Config.readChinese("urlName");//"系统名称";
        if(!urlName.isEmpty()){
            HtmlUtil.writerSuccessJson(response, urlName);
        }else {
            HtmlUtil.writerFailJson(response, "配置文件缺少系统名称");
        }
    }
}